'use client';

import type { transError } from '@/service/error';
import { type SetStateAction, useState, useTransition } from 'react';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';

type Result = {
  error: ReturnType<typeof transError> | null;
};

export default function ConfirmButton({
  button,
  title = '确认',
  description = '确认操作吗?',
  onClick,
}: {
  button:
    | ((setOpen: React.Dispatch<SetStateAction<boolean>>) => React.ReactNode)
    | React.ReactNode;
  title?: string;
  description?: string;
  onClick: () => Result | Promise<Result>;
}) {
  const [isPending, startTransition] = useTransition();
  const [open, setOpen] = useState(false);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      {typeof button === 'function' ? (
        button(setOpen)
      ) : (
        <DialogTrigger asChild>{button}</DialogTrigger>
      )}
      <DialogContent>
        <DialogHeader className="space-y-4">
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>
        <div className="flex justify-center sm:justify-end gap-5">
          <DialogClose asChild>
            <Button variant="ghost">算了</Button>
          </DialogClose>
          <Button
            disabled={isPending}
            onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
              e.stopPropagation();
              e.preventDefault();
              startTransition(async () => {
                const { error } = await onClick();
                !error && setOpen(false);
              });
            }}
            className="flex items-center gap-2"
          >
            {isPending && <span className="animate-spin i-ri-loader-5-fill" />}
            确定
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
